const UsersRepository = require('../repositories/usersRepositories')
const { formatDateTime, getTimeDifference } = require('../utils/dateFormat')
const bcrypt = require('bcrypt');
const config = require('../config') // 引入配置文件提取密钥
const SECRET_KEY = config.jwtSecret // 从配置文件中获取密钥
const jwt = require('jsonwebtoken')

class UsersServices {
  // 提取通用的响应处理函数
  handleResponse(data, error, notFoundMessage = '用户未注册') {
    if (error) {
      return {
        code: 1,
        msg: error.message,
        statusCode: error.statusCode || 500,
      }
    }
    if (!data) {
      return {
        code: 1,
        msg: notFoundMessage,
        statusCode: 404,
      }
    }
    return {
      code: 0,
      data: data, // 返回数据
    }
  }

  /**
   * 用户登录
   * @param {string} account - 用户账号
   * @param {string} password - 用户密码
   * @returns {Promise<Object>} - 返回响应对象
   */
  async login(account, password) {
  try {
    // 检查参数是否为空
    if (!account || !password) {
      return {
        code: 1,
        msg: '账号和密码不能为空',
        statusCode: 400,
      }
    }

        // 检查账号和密码的长度是否大于 6
    if (account.length < 6 || password.length < 6) {
      return {
        code: 1,
        msg: '格式错误：账号和密码长度必须大于 6',
        statusCode: 400,
      }
    }

    // 查询用户
    const user = await UsersRepository.getUserByAccount(account);
    if (!user) {
      return {
        code: 1,
        msg: '用户不存在,请注册！',
        statusCode: 404,
      }
    }

    // 检查数据库中是否有密码
    if (!user.password) {
      return {
        code: 1,
        msg: '用户密码缺失，请联系管理员',
        statusCode: 500,
      }
    }

    // 验证密码
    const isPasswordValid = await bcrypt.compare(password, user.password);
    if (!isPasswordValid) {
      return {
        code: 1,
        msg: '密码错误'
      }
    }

    // 生成 JWT Token
    const token = jwt.sign(
      { id: user.id, account: user.account }, // 载荷
      SECRET_KEY, // 密钥
      { expiresIn: '1h' } // 过期时间
    )

    // 返回登录成功信息（不包含 Token）
    return {
      code: 0,
      data: {
        token,
        user: {
          id: user.id,
          nickname: user.nickname,
          account: user.account,
          avatar: user.avatar,
          state: user.state,
          registerTime: formatDateTime(user.createdAt),
          duration: getTimeDifference(user.createdAt)
        },
      },
    }
  } catch (error) {
    return {
      code: 1,
      msg: '登录失败',
      statusCode: 500,
      error: error.message,
    };
  }
}

  /**
   * 注册新用户
   * @param {Object} userData - 用户数据
   * @returns {Promise<Object>} - 返回响应对象
   */
  async addNewUser(userData) {
    try {
       // 查询用户
       const { account } = userData
      const user = await UsersRepository.getUserByAccount(account)
      if (user) {
        return {
          code: 1,
          msg: '用户已经存在,请更换账号后重试！',
          statusCode: 404,
        }
      }
      const { password, ...rest } = userData

      // 检查密码是否为空
      if (!password) {
        return {
          code: 1,
          msg: '密码不能为空',
          statusCode: 400,
        }
      }

      // 加密密码
      const salt = await bcrypt.genSalt(10) // 生成盐
      const hashedPassword = await bcrypt.hash(password, salt) // 加密密码

      const currentTime = new Date()
      const newUserData = {
        ...rest,
        password: hashedPassword, // 添加加密后的密码
        createdAt: currentTime,
        updatedAt: currentTime,
      }

      // 创建用户
      const newUser = await UsersRepository.addNewUser(newUserData)

      // 移除敏感字段
      const userResponse = { ...newUser.get({ plain: true }) }
      delete userResponse.password // 移除 password 字段

      return {
        code: 0,
        data: userResponse,
      }

    } catch (error) {
      return {
        code: 1,
        msg: '注册失败',
        statusCode: 500,
        error: error.message,
      };
    }
  }

  async delUserById(id) {
    try {
      const result = await UsersRepository.delUserById(id);
      return result
        ? this.handleResponse('用户注销成功')
        : this.handleResponse(null, null, '用户未注册')
    } catch (error) {
      return this.handleResponse(null, error)
    }
  }

  async updateUserById(id, userData) {
    try {
      // 自动更新 updatedAt 字段
      const updatedUserData = {
        ...userData,
        updatedAt: new Date(),
      };

      const result = await UsersRepository.updateUserById(id, updatedUserData);
      return result
        ? this.handleResponse('用户更新成功')
        : this.handleResponse(null, null, '用户不存在')
    } catch (error) {
      error.statusCode = 400; // 设置状态码
      return this.handleResponse(null, error)
    }
  }

  async getAllUsers() {
    try {
      const users = await UsersRepository.getAllUsers()
      return this.handleResponse(users)
    } catch (error) {
      return this.handleResponse(null, error)
    }
  }

  async getUserById(id) {
    try {
      const user = await UsersRepository.getUserById(id)
      return this.handleResponse(user);
    } catch (error) {
      return this.handleResponse(null, error)
    }
  }

  async getUserByAccount(account) {
    try {
      const user = await UsersRepository.getUserByAccount(account)
      return this.handleResponse(user)
    } catch (error) {
      return this.handleResponse(null, error)
    }
  }
}

module.exports = new UsersServices();